import React, { lazy, Suspense } from 'react';
import { Spin } from 'antd';
import { NonIndexRouteObject } from 'react-router-dom';
import { routes } from '@/router';
import type { RouterRes } from '@/service/login/type';

export interface IRouteObject extends Omit<NonIndexRouteObject, 'children'> {
	name?: string;
	meta?: { title: string };
	hidden?: boolean;
	children?: IRouteObject[];
}

// 映射用户菜单生成个路由表
const modules = import.meta.glob<{ default: () => JSX.Element }>('/src/views/**/*.tsx');
const DefaultCom = () => {
	return <span>没有找到页面组件</span>;
};

export function mapRouters(userMenus: RouterRes[]): IRouteObject[] {
	const routes: IRouteObject[] = [];

	function _recurseGetRoute(menus: RouterRes[]) {
		for (const menu of menus) {
			if (!menu.children) {
				// const pathList = menu.component.split('/');
				const com = modules['/src/views' + menu.component + '.tsx'];

				const route: IRouteObject = {
					name: menu.name,
					path: menu.path,
					meta: { title: menu.meta.title },
					hidden: menu.hidden ?? false,
					element: lazyLoad(
						lazy(com === undefined ? () => Promise.resolve({ default: DefaultCom }) : com)
					)
					// element: lazyLoad(menu.component)
				};
				routes.push(route);
			} else {
				_recurseGetRoute(menu.children);
			}
		}
	}
	_recurseGetRoute(userMenus);

	return routes;
}

// 懒加载路由模块
export const lazyLoad = (Comp: React.LazyExoticComponent<() => JSX.Element>) => {
	return (
		<Suspense
			fallback={
				<Spin
					size="large"
					style={{
						display: 'flex',
						alignItems: 'center',
						justifyContent: 'center',
						height: '100%'
					}}
				/>
			}
		>
			<Comp />
		</Suspense>
	);
};

// 向目标路由中的children增加路由
export const addRouter = (name: string, addRoutes: IRouteObject[]) => {
	if (name) {
		const target = routes.find((item) => item.name === name);

		if (target) {
			// 遍历children中是否已存在，防止重复添加
			const newRoutes = addRoutes.filter((route) =>
				target.children?.find((item) => route.path !== item.path)
			);
			if (newRoutes.length) target?.children?.push(...newRoutes);
		}
	} else {
		routes.push(...addRoutes);
	}
};
